package controller;


import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.cglib.core.Constants;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import pojo.SysUser;
import service.SysUserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static org.springframework.cglib.core.Constants.*;

/**
 * SysUserController
 *
 * @author boy
 * @since 2023/10/25
 */
@Controller
@RequestMapping("/user")
public class SysUserController {

    private static final String USER_SESSION = null;
    private Logger logger = Logger.getLogger(SysUserController.class);
    private ArrayList<SysUser> sysUsers = new ArrayList<>();
    private ArrayList<SysUser> querylist = new ArrayList<>();
    @Resource
    private SysUserService sysUserService;

    /**
     * 跳转到登录页面
     *
     * @return
     */
    @RequestMapping(value = "/toLogin")
    public String login() {
        logger.info("跳转到登录页面");
        return "login";
    }

    /**
     * 登录
     *
     * @param account
     * @param password
     * @return
     */
    @PostMapping("/login")
    public String doLogin(HttpServletRequest request, HttpSession session, @RequestParam String account, @RequestParam String password) {
        logger.debug("登录方法");
        entity.SysUser sysUser = sysUserService.login(account, password);
        if (null != sysUser) {
            session.setAttribute(USER_SESSION, sysUser);
            return "redirect:/user/toMain";
        } else {
            request.setAttribute("error", "用户名密码不正确");
            return "login";
        }
    }

    /**
     * 跳转到首页
     *
     * @return
     */
    @RequestMapping("/toMain")
    public String main(HttpSession session) {
        if (session.getAttribute(USER_SESSION) == null) {
            return "redirect:/user/toLogin";
        }
        return "frame";
    }

    public SysUserController() {
        try {
            sysUsers.add(new SysUser(5, "zhaojing", "赵静", "555555", 1, "13054784445", "上海宝山区",
                                     1, 1, new Date(), 1, new Date()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/list")
    public String list(Model model, String queryRealName, Integer queryRoleId, @RequestParam(defaultValue = "1") Integer pageIndex) {
        List<SysUser> userList = null;
        try {
            int pageSize = Constants.pageSize;
            int totalCount = sysUserService.getUserCount(queryRealName, queryRoleId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("当条件为空时，查询用户信息");
        return "redirect:/user/toSysError";
        querylist.clear();
        querylist.addAll(sysUsers);
        model.addAttribute("querylist", querylist);
        return "sysUser/sysUserList";
    }

    public String list(@RequestParam(value = "realName", required = false) String realName, Model model) {
        logger.info("查询条件【realName】=" + realName + "查询用户信息");
        querylist.clear();
        if (realName != null && !realName.equals("")) {
            for (SysUser sysUser : querylist) {
                if (sysUser.getRealName().indexOf(realName) != -1) {
                    querylist.add(sysUser);
                }
            }
        } else {
            querylist.addAll(sysUsers);
        }
        model.addAttribute("querylist", querylist);
        return "sysUser/sysUserList";
    }

    /**
     * 捕获异常信息，跳转到error页面
     */
    public String handlerException(RuntimeException e, HttpServletRequest req) {
        req.setAttribute("e", e);
        return "error";
    }

    /**
     * 一个抛出异常的接口
     */
    public String exLogin(@RequestParam String account, @RequestParam String password) {
        entity.SysUser user = sysUserService.login(account, password);
        if (null == user) {
            throw new RuntimeException("用户名或密码不正确");
        }
        return "redirect:/user/toMain";
    }

    /**
     * 跳转到异常处理页面
     */
    @RequestMapping(value = "/toSysError")
    public String sysError() {
        return "sysError";
    }

    /**
     * 跳转到添加用户页面
     */
    @GetMapping("/toAdd")
    public String toAdd() {
        return "sysUser/add";
    }

    public String add(entity.SysUser sysUser, HttpSession session) {
        sysUser.setCreatedUserId(((SysUser) session.getAttribute(Constants.USER_SESSION)).getId());
        if (sysUserService.add(sysUser)) {
            return "redirect:/user/list";
        }
        return "sysUser/add";
    }

    /**
     * 查询用户详情
     */
    @GetMapping("/view/{id}")
    public String view(@PathVariable String id, Model model) {
        logger.debug("根据id查询用户详情" + id);
        entity.SysUser sysUser = sysUserService.getUserById(id);
        model.addAttribute(sysUser);
        return "sysUser/view";
    }

    public String toUpdate(@RequestParam String uid, Model model) {
        logger.debug("跳转到修改用户");
        entity.SysUser sysUser = sysUserService.getUserById(uid);
        model.addAttribute(sysUser);
        return "sysUser/update";
    }

    /**
     * 修改用户信息
     */
    @PostMapping("/update")
    public String update(SysUser sysUser, HttpSession session) {
        logger.debug("修改用户信息");
        sysUser.setUpdatedUserId(((SysUser) session.getAttribute(Constants.USER_SESSION)).getId());
        if (sysUserService.update(sysUser)) {
            return "redirect:/user/list";
        }
        return "sysUser/update";
    }

    /**
     * 跳转到添加用户页面
     */
    public String toAdd(@ModelAttribute("sysUser") SysUser sysUser) {
        return "sysUser/add";
    }

    /**
     * 多文件上传
     */
    @PostMapping("/add")
    public String add(SysUser sysUser, HttpSession session, HttpServletRequest request,
                      @RequestParam(value = "idPic",required = false)MultipartFile[] idPic) {
        String idPicpath = null;
        String workPicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
        logger.info("文件储存路径" + path);
        for (int i = 0; i < idPic.length; i++) {
            MultipartFile pic = idPic[i];
            if (!pic.isEmpty()) {
                if (i == 0) {
                    errorInfo = "uploadFileError";
                } else if (i == 1) {
                    errorInfo = "uploadWpError";
                }
                String originalFile = pic.getOriginalFilename();
                logger.info("原文件名" + originalFile);
                String prefix = FilenameUtils.getExtension(originalFile);
                logger.debug("源文件后缀" + prefix);
                int filesize = 50000;
                logger.debug("文件大小" + pic.getSize());
                if (pic.getSize() > filesize) {
                    request.setAttribute("uploadFileError", "上传大小不得超过500kb");
                    return "sysUser/add";
                } else if (prefix.equalsIgnoreCase("jsp") || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal." + prefix;
                    logger.debug("新生成的文件名称" + fileName);
                    File targetFile = new File(path);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }
                    try {
                        pic.transferTo(new File(targetFile, fileName));
                    } catch (IOException e) {
                        e.printStackTrace();
                        request.setAttribute("uploadFileError", "上传失败");
                        flag = false;
                    }
                    if (i == 0) {
                        idPicpath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                    } else if (i == 1) {
                        workPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                    }
                    logger.debug("idPicPath" + idPicpath);
                    logger.debug("workPicPath" + workPicPath);
                } else {
                    request.setAttribute("uploadFileError", "上传图片格式不正确");
                    return "sysUser/add";
                }
            }
        }
        if (flag) {
            sysUser.setCreatedUserId(((SysUser) session.getAttribute(Constants.USER_SESSION)).getId());
            sysUser.setIdPicPath(idPicpath);
            sysUser.setWorkPicPath(workPicPath);
            if (sysUserService.add(sysUser)) {
                return "redirect:/user/list";
            }
        }
            return "sysUser/add";
        }
}
